package com.compass.mobile.widget

import LogUtil
import UserInfoManager
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import androidx.activity.viewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import asActivity
import com.compass.mobile.R
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.callback.OnPatientItemClickListener
import com.compass.mobile.databinding.LayoutCommonViewBinding
import com.compass.mobile.framework.constant.OK_ACTION
import com.compass.mobile.framework.constant.PATIENT_ID
import com.compass.mobile.framework.constant.PATIENT_SWITCH
import com.compass.mobile.framework.constant.REFRESH_PATIENT
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.ext.visible
import com.compass.mobile.framework.utils.DateUtils
import com.compass.mobile.framework.utils.FocusViewUtils
import com.compass.mobile.framework.utils.LiveDataBus
import com.compass.mobile.framework.utils.TipsToast
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.PatientBean
import com.compass.mobile.models.Title
import com.compass.mobile.presenters.TitlePresenter
import com.compass.mobile.ui.activity.MyOrderActivity
import com.compass.mobile.ui.activity.NotificationActivity
import com.compass.mobile.ui.activity.PatientsActivity
import com.compass.mobile.ui.activity.PersonalCenterActivity
import com.compass.mobile.ui.dialog.ChoosePatientDialog
import com.compass.mobile.ui.dialog.CommonMessageDialog
import com.compass.mobile.ui.dialog.CustomerServiceCode
import com.compass.mobile.ui.viewModel.UserViewModel
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.RequestCallback
import com.netease.nimlib.sdk.auth.AuthService
import com.netease.nimlib.sdk.auth.LoginInfo
import getStringFromResource
import setUrlCircle
import toBeanOrNull
import toJson

/**
 * Description： 顶部自定义view
 * Date:2024/6/3 21:33
 */
class TopActionBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {


    private lateinit var mBinding: LayoutCommonViewBinding

    private val userViewModel: UserViewModel by context.asActivity.viewModels()

    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            if (!UserInfoManager.isHaveDefPatient()) {
                addPatientDialog()
                return
            }

            when (position) {
                0 -> {
                    //我的订单
                    MyOrderActivity.start(context)
                }

                1 -> {
                    //通知
                    NotificationActivity.start(context)
                }

                2 -> {
                    //个人中心
                    PersonalCenterActivity.start(context)
                }

                3 -> {
                    //客服二维码
                    CustomerServiceCode.Builder(getContext().asActivity, OK_ACTION).show()
                }
            }

        }
    }

    init {
        init(context)
    }

    /**
     * 初始化
     *
     * @param context 上下文
     * @param attrs   attrs
     */
    private fun init(context: Context) {
        val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        mBinding = LayoutCommonViewBinding.inflate(inflater, this, true)
        initTitle(context)
    }

    private fun addPatientDialog() {
        CommonMessageDialog.Builder(context.asActivity)
            .setTitle("温馨提示")
            .setMessage("您还没有添加就诊人，是否去添加？")
            .setConfirm(getStringFromResource(R.string.default_confirm))
            .setCancel(getStringFromResource(R.string.default_cancel))
            .setonCancelListener {
                it?.dismiss()
            }
            .setonConfirmListener {
                PatientsActivity.start(context.asActivity)
                it?.dismiss()
            }.create().show()
    }

    @SuppressLint("RestrictedApi")
    fun initTitle(context: Context) {
        mBinding.gridTitle.setHorizontalSpacing(dpToPx(10))
        val arrayObjectAdapter = ArrayObjectAdapter(TitlePresenter())
        val itemBridgeAdapter = MyBridgeAdapter(context, arrayObjectAdapter, onItemClickListener)
        mBinding.gridTitle.setAdapter(itemBridgeAdapter)
        arrayObjectAdapter.addAll(0, titleList)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )

//        FocusViewUtils.scaleView(mBinding.llSwitchPatients, 0)
        FocusViewUtils.scaleView(mBinding.llLeft, 0)

        mBinding.llSwitchPatients.onClick {
            if (!UserInfoManager.isHaveDefPatient()) {
                addPatientDialog()
                return@onClick
            } else {

                val patients = UserInfoManager.getPatientList()?.toBeanOrNull<MutableList<PatientBean>>()
                if (patients != null) {
                    LogUtil.e("${patients.toJson()}")
                }
                patients?.let {
                    patientList = it
                    showChoosePatientDialog()
                }
                userViewModel.gePatientsForBar()

            }
        }

        userViewModel.patientBarLiveData.observe(context.asActivity) {
            it?.let { list->
                UserInfoManager.savePatientList(list.toJson())
            }
        }

        mBinding.llLeft.onClick {
            val isBrowserInstalled = isAppInstalled("com.starcor.browser.app.jkyl");
            if (isBrowserInstalled) {
                val intent =
                    Intent(Intent.ACTION_VIEW, Uri.parse("native://agedcare.large/order-select"))
                context.asActivity.startActivity(intent)
            } else {
                TipsToast.showTips("请先安装爱家健康")
            }
        }
        userViewModel.refreshPatientLiveData.observe(context.asActivity) {
            patientBean?.let {
                doLoginIM(it)
                //PATIENT_SWITCH
                LiveDataBus.get().with(PATIENT_SWITCH).postValue(PATIENT_SWITCH)
                //默认就诊人切换成功，需要将本地缓存的默认就诊人
                val patients = UserInfoManager.getPatientList()?.toBeanOrNull<MutableList<PatientBean>>()
                if (!patients.isNullOrEmpty()) {
                    patients.forEach{item->
                        run {
                            if (item.id == it.id) {
                                item.defaultStatus = 1
                            } else {
                                item.defaultStatus = 0
                            }
                        }
                    }
                    val patientList =  patients.sortedByDescending{item->item.defaultStatus}
                    LogUtil.e("patients:${patientList.toJson()}")
                    UserInfoManager.savePatientList(patientList.toJson())
                }
            }
        }
        setDefaultPatientInfo()
    }

    fun setDefaultPatientInfo() {
        if (UserInfoManager.isHaveDefPatient()) {
            val patientBean = UserInfoManager.getPatientInfo()
            patientBean?.let {
                mBinding.apply {
                    ivPatientAvatar.setUrlCircle(it.avatar)
                    // 1-男 2-女 0-未知
                    val sex = when (it.sex) {
                        "1" -> "男"
                        "2" -> "女"
                        else -> "未知"
                    }
                    var age = "年龄：${DateUtils.formatAge2(it.birthday)} 岁"
                    tvPatientName.text = "${it.name} ${sex}  ${age}"
                    ivPatientAvatar.visible()
                }
            } ?: kotlin.run {
                mBinding.apply {
                    tvPatientName.text = "暂无就诊人"
                    ivPatientAvatar.gone()
                }
            }
        } else {
            mBinding.apply {
                tvPatientName.text = "暂无就诊人"
                ivPatientAvatar.gone()
            }
        }
    }

    private var patientBean:PatientBean?=null
    private var patientList: MutableList<PatientBean> = mutableListOf()//包装集合
    private fun showChoosePatientDialog() {
        val choosePatientDialog =
            ChoosePatientDialog.Builder(context.asActivity, patientItemClickListener, patientList)
        choosePatientDialog.show()
    }



    /**
     *  患者item点击事件,将当前患者设置为默认患者
     */
    private val patientItemClickListener: OnPatientItemClickListener =
        object : OnPatientItemClickListener {
            override fun onItemClick(patient: PatientBean, view: View) {
                patientBean=patient
                UserInfoManager.savePatientInfo(patient.toJson())
                setDefaultPatientInfo()
                //退出当前登录的就诊人
                NIMClient.getService(AuthService::class.java).logout()
                userViewModel.switchPatients(patient.id)
                //更新一次就诊人数据
                userViewModel.gePatientsForBar()
            }
        }

    /**
     * 登录IM
     */
    private fun doLoginIM(patientBean: PatientBean) {
        val info = LoginInfo(patientBean.wyyxAccId, patientBean.wyyxToken)
        val callback: RequestCallback<LoginInfo?> = object : RequestCallback<LoginInfo?> {
            override fun onSuccess(param: LoginInfo?) {
//                LogUtil.d("LoginInfo======onSuccess====00===${patientBean.id}")
                UserInfoManager.putString(PATIENT_ID,patientBean.id)
//                LogUtil.d("LoginInfo======onSuccess====11==${UserInfoManager.getString(PATIENT_ID)}")
                UserInfoManager.saveImUserAccount(param?.account)
                UserInfoManager.saveImToken(param?.token)
                TipsToast.showTips("就诊人切换成功")
            }

            override fun onFailed(code: Int) {


            }

            override fun onException(exception: Throwable) {

            }
        }
        //执行手动登录
        NIMClient.getService(AuthService::class.java).login(info).setCallback(callback)


    }



    private fun isAppInstalled(packageName: String): Boolean {
        try {
            context.asActivity.packageManager.getPackageInfo(packageName, 0)
            return true
        } catch (e: PackageManager.NameNotFoundException) {
            return false
        }
    }

    /**
     * 设置切换问诊人view显示状态
     */
    fun setPatientViewVisible(visible: Boolean) {
        if (visible) {
            mBinding.llSwitchPatients.visible()
        } else {
            mBinding.llSwitchPatients.gone()
        }
    }

    companion object {
        //模拟数据
        val titleList: List<Title?>
            get() {
                val titleList: MutableList<Title?> = ArrayList()
                titleList.add(Title("问诊订单"))
                titleList.add(Title("通知"))
                titleList.add(Title("个人中心"))
                titleList.add(Title("客服"))
                return titleList
            }
    }
}